package com.lkx.service.strategy.impl;

import com.lkx.dto.RequestLimitDTO;
import com.lkx.enums.CloudLimitTypeEnum;
import com.lkx.service.strategy.CloudLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Service
public class LeakyBucketCloudLimitServiceImpl implements CloudLimitService {

    @Autowired
    private ResourcePatternResolver resourcePatternResolver;

    @Value("${cloud.limit.scan-package:}")
    private String scanPackage;

    @Override
    public boolean checkRequestLimit(RequestLimitDTO requestLimitDTO) {
        return false;
    }

    @Override
    public CloudLimitTypeEnum getLimitType() {
        return CloudLimitTypeEnum.LEAKY_BUCKET;
    }


    /**
     * 漏桶线程池
     * @return 线程池实例化对象
     */
    @PostConstruct
    @Bean(name = "leakyBucketPopThreadPoolScheduler")
    public ThreadPoolTaskScheduler leakyBucketPopThreadConfig(){
        //扫描出所有使用了自定义注解并且限流类型为漏桶算法的方法
        List<RequestLimitDTO> list = this.getTokenLimitList(resourcePatternResolver,CloudLimitTypeEnum.LEAKY_BUCKET,scanPackage);
        if(null == list || list.isEmpty()){
            log.warn("未扫描到使用【{}】的方法,限流未开启...",CloudLimitTypeEnum.LEAKY_BUCKET.getDesc());
            return null;
        }else{
            ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
            scheduler.setPoolSize(1);
            scheduler.setThreadNamePrefix("漏桶线程");
            log.info("=========>>>>>>>漏桶线程池实例化");
            return scheduler;
        }

    }
}
